package handler

import (
	"alipay/api/handler/request"
	"alipay/internal/dao"
	"alipay/internal/model"
	jwt2 "alipay/pkg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": "验证失败",
			"data":    err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{}, &user)
	if user.Account == req.Account {
		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": "此用户已存在",
			"data":    nil,
		})
		return
	}
	user = model.User{
		Account:  req.Account,
		PassWord: req.Password,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": "注册失败",
			"data":    nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "ok",
		"data":    user,
	})
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": "验证失败",
			"data":    err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Account: req.Account,
	}, &user)
	if user.Account != req.Account {
		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": "没有此用户",
			"data":    nil,
		})
		return
	}
	token, _ := jwt2.NewJWT("2211a").CreateToken(jwt2.CustomClaims{
		ID: uint(user.Id),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 864000,
		},
	})
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "ok",
		"data":    token,
	})
}
